*****************************************************
** Make time series dataset 
*****************************************************

use ../processed_data/raw_data_all_years.dta, clear
** set up indicators for what types of deaths they were

** heroin and anything else
forvalues i = 1(1)20 {
	gen byte heroin`i' = (cond`i'=="T401")
}
egen byte any_heroin = rowmax(heroin*)
drop heroin*

** opioid and anything else
forvalues i = 1(1)20 {
	gen byte opioid`i' = (cond`i'=="T402") | (cond`i'=="T403") | (cond`i'=="T404")
}
egen byte any_opioid = rowmax(opioid*)
drop opioid*

** synthetic opioids and anything else
forvalues i = 1(1)20 {
	gen byte synthetic`i' = (cond`i'=="T404")
}
egen byte any_synthetic = rowmax(synthetic*)
** non-synthetic opioid
forvalues i = 1(1)20 {
	gen byte nsynthetic`i' = (cond`i'=="T402") | (cond`i'=="T403")
}
egen byte any_nsynthetic = rowmax(nsynthetic*)
** combinations of synthetic
** find records with both synthetic and non-synthetic opioids
gen syn_opioid = (any_synthetic+any_nsynthetic)==2
drop synthetic* nsynthetic*
** synthetic and heroin
gen syn_heroin = (any_heroin+any_synthetic)==2
** synthetic with heroin and/or other opioid
gen syn_horo = (syn_opioid + syn_heroin)>=1
** synthetic, neither heroin nor other opioids
gen syn_nohnoo = any_synthetic - any_heroin - any_nsynthetic
replace syn_nohnoo = 0 if syn_nohnoo<0

** heroin without synthetic opioids
gen heroin_nosynths = any_heroin - any_synthetic
replace heroin_nosynths = 0 if heroin_nosynths<0
** opioids without synthetic opioids
gen opioid_nosynths = any_opioid - any_synthetic
replace opioid_nosynths = 0 if opioid_nosynths<0


drop cond*

collapse (sum) any_heroin any_opioid any_synthetic heroin_nosynths ///
opioid_nosynths syn_heroin syn_opioid syn_nohnoo syn_horo, ///
by(death_year death_month)

rename death_year year
rename death_month month

label var syn_heroin "synthetic, heroin"
label var syn_opioid "synthetic, opioid"
label var syn_nohnoo "synthetic, no heroin no opioid"
label var syn_horo "synthetic, either heroin or opioid"

compress
sort year month

save ..\processed_data\ts_dataset.dta, replace

export excel using ..\processed_data\time_series_deaths.xlsx, replace firstrow(variables)

